package com.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springboot.common.R;
import com.springboot.pojo.Employee;
import com.springboot.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request , @RequestBody Employee employee) {
        log.info("login请求参数：{}", employee);
        //1.将页面 提交的密码password 进行加密出理
        String password = employee.getPassword();
        //加密算法
       password = DigestUtils.md5DigestAsHex(password.getBytes());
        employee.setPassword(password);
        //2.根据页面提交的用户名userrname 查询数据库
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp=employeeService.getOne(wrapper);

        //3.判断查询结果是否为空
        if(emp ==null){return R.error("登录失败，用户名或密码错误");}

        //4.判断密码是否正确
        if (!emp.getPassword().equals(password)){
            return R.error("登录失败，用户名或密码错误");
        }
       //5.查看员工状态码是否被禁用
        if(emp.getStatus() ==0){
            return  R.error("登录失败，账号已被禁用");
        }
        //6.登录成功，将员工信息放入session
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //清除session中的id员工信息
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> addEmployee(HttpServletRequest request,@RequestBody Employee employee) {
         //设置初始化密码，使用md5加密
         String password=DigestUtils.md5DigestAsHex(("123456").getBytes());
          employee.setPassword(password);
        //设置员工创建时间和更新时间
        //  employee.setCreateTime(LocalDateTime.now());
          //employee.setUpdateTime(LocalDateTime.now());
          //设置员工创建人和更新人
        Long empid = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(empid);
        employee.setUpdateUser(empid);
        //保存员工信息
        employeeService.save(employee);
        //返回成功信息
        return R.success("新增员工成功");
    }

    @GetMapping("/page")
    public  R<Page> getpage(int page,int pageSize,String name){
        System.out.println("page:"+page+"pagesize:"+pageSize+"name:"+name);
        //分页查询
        Page employeePage=new Page(page,pageSize);
        LambdaQueryWrapper<Employee> wrapper=new LambdaQueryWrapper<>();//条件构造器
        wrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);//模糊查询
        wrapper.orderByDesc(Employee::getUpdateTime);//排序
        employeeService.page(employeePage,wrapper);//执行sql查询
        return  R.success(employeePage);
    }

    /**
     * ID更新员工信息
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> updateEmployee(HttpServletRequest request,@RequestBody Employee employee) {
        //设置员工更新时间
       // employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));
        long id = Thread.currentThread().getId();
        log.info("updateEmployee线程id：{}", id);
        //更新员工信息
        employeeService.updateById(employee);
        //返回成功信息
        return R.success("更新员工成功");
    }
    /**
     * ID查询员工信息
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R<String> deleteEmployee(@PathVariable("id") Long id) {
        //删除员工信息
        employeeService.removeById(id);
        //返回成功信息
        return R.success("删除员工成功");
    }


    @GetMapping("/{id}")
    public R<Employee> getEmployee(@PathVariable("id") Long id) {
        Employee employee = employeeService.getById(id);
        if (employee == null){

            return R.error("查询失败，员工不存在");
        }
        return R.success(employee);
    }


}
